package com.lefull.lefullbase.utils.helper;

import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;

/**
 * Created by Jack on 2016/11/18.
 */

public class LruCacheUtil {
    private static int MAXMEMONRY = (int) Runtime.getRuntime().maxMemory();
    private static LruCache<Integer, Bitmap> mMemoryCache = new LruCache<Integer, Bitmap>(
            MAXMEMONRY / 8) {
        @Override
        protected int sizeOf(Integer key, Bitmap bitmap) {
            // 重写此方法来衡量每张图片的大小，默认返回图片数量。
            return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
        }


    };
    private static final String TAG = "LruCacheUtil";


    public static void clearCache() {
        if (mMemoryCache != null) {
            if (mMemoryCache.size() > 0) {
                Log.d("CacheUtils",
                        "mMemoryCache.size() " + mMemoryCache.size());
                mMemoryCache.evictAll();
                Log.d("CacheUtils", "mMemoryCache.size()" + mMemoryCache.size());
            }
            mMemoryCache = null;
        }
    }

    public static synchronized void addBitmapToMemoryCache(int key, Bitmap bitmap) {
        if (mMemoryCache.get(key) == null) {
            if (key != 0 && bitmap != null)
                mMemoryCache.put(key, bitmap);
        } else
            Log.w(TAG, "the res is aready exits");
    }

    public static synchronized Bitmap getBitmapFromMemCache(int key) {
        Bitmap bm = mMemoryCache.get(key);
        if (key != 0) {
            return bm;
        }
        return null;
    }

    /**
     * 移除缓存
     *
     * @param key
     */
    public static synchronized void removeImageCache(int key) {
        if (key != 0) {
            if (mMemoryCache != null) {
                Bitmap bm = mMemoryCache.remove(key);
                if (bm != null)
                    bm.recycle();
            }
        }
    }
}
